package com.mycat.web.content.shiro;

import com.mycat.dao.entity.ucenter.Customer;
import com.mycat.service.constant.auth.AdminState;
import com.mycat.service.constant.ucenter.CustomerState;
import com.mycat.service.ucenter.CustomerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义shiro Realm,进行登录验证,授权
 *
 * @author Roger
 */
public class CustomerUserRealm extends AuthorizingRealm {

    public static final String SESSION_LOGIN_USER = "SESSION_LOGIN_USER";
    public static final String SESSION_LOGIN_USER_ID = "SESSION_LOGIN_USER_ID";

    @Autowired
    private CustomerService customerService;

    /**
     * 初始化加密认证机制
     */
    public CustomerUserRealm() {
    }

    /**
     * 身份认证/登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        final String userName = (String) token.getPrincipal(); // principals：身份，即主体的标识属性，可以是任何东西，如用户名、邮箱等
        Customer customer = customerService.findCustomer(new Customer(){{
            this.setUserName(userName);
        }});
        if (null == customer) {
            throw new UnknownAccountException("当前用户不存在");
        }
        if (CustomerState.locked.getCode().equalsIgnoreCase(customer.getState())) {
            throw new LockedAccountException(AdminState.locked.getMessage());
        }
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(SESSION_LOGIN_USER, customer);
        session.setAttribute(SESSION_LOGIN_USER_ID, customer.getId());
        return new SimpleAuthenticationInfo(userName, customer.getPswd(), ByteSource.Util.bytes(customer.getSalt()),getName());
    }

    /**
     * 授权，即权限验证，验证某个已认证的用户是否拥有某个权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Set<String> roleStrings = new HashSet<>();
        Set<String> permissionStrings = new HashSet<>();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roleStrings);
        authorizationInfo.setStringPermissions(permissionStrings);
        return authorizationInfo;
    }
}